package com.hmdp.utils;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * 全局唯一 id
 */
@Component
@RequiredArgsConstructor
public class RedisIdWorker {

    private final StringRedisTemplate stringRedisTemplate;
    //开始时间戳  2004,2,2
    private final Long INITIAL_TIME=1075680000L;
    //序列号的位数
    private final Integer COUNT_BIT=32;

    /**
     * 生成全局唯一ID的下一个ID
     * @param keyPrefix 相关业务前缀
     * @return
     */
    public long nextId(String keyPrefix){
        // 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - INITIAL_TIME;

        // 生成序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 使用icr:[业务前缀]:[年]:[月]:[日]  作为key
        String key = "icr:" + keyPrefix + ":" + date;
        long count = stringRedisTemplate.opsForValue().increment(key);

        // 拼接并返回
        return timestamp << COUNT_BIT | count;
    }




}
